package com.noble.glamour.ui.user.my.auth;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.library.base.BaseActivity;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.ChineseFilter;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;

import java.lang.Thread.State;
import java.lang.ref.WeakReference;

/**
 * 手机验证页面
 */
public class PhoneVerifyAct extends BaseActivity implements OnClickListener, RequestComplete {
    private EditText edtPhone, et_code;
    private TextView bt_send_code;

    private String phone, code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f1_activity_phoneverify);
        initView();
    }

    private void initView() {
        setBackView(getString(R.string.auth_phone));
        setTitleRight(getString(R.string.title_right_submit), this);
        edtPhone = (EditText) findViewById(R.id.edt_phoneverify_phone);
        et_code = (EditText) findViewById(R.id.edt_phoneverify_note);
        bt_send_code = (TextView) findViewById(R.id.btn_phoneverify_begin);
        bt_send_code.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_phoneverify_begin:
                if (validPhone()) {
                    LoadingDialog.show(this, getString(R.string.code_sending));
                    ModuleMgr.getLoginMgr().reqSendCode(phone, this);
                }
                break;

            case R.id.base_title_right_txt:
                if (validPhone() && validInput()) {
                    LoadingDialog.show(this, getString(R.string.tip_loading_submit));
                    ModuleMgr.getCenterMgr().mobileAuthEx(phone, code, this);
                }
                break;
            default:
                break;
        }
    }

    private boolean validPhone() {
        phone = edtPhone.getText().toString();
        if ("".equals(phone)) {
            PToast.showShort(getResources().getString(R.string.toast_phone_isnull));
            return false;
        }
        if (!ChineseFilter.isPhoneNumber(phone)) {
            PToast.showShort(getResources().getString(R.string.toast_phone_iserror));
            return false;
        }
        return true;
    }

    private boolean validInput() {
        code = et_code.getText().toString();
        if (TextUtils.isEmpty(code)) {
            PToast.showShort(getResources().getString(R.string.toast_code_isnull));
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoadingDialog.closeLoadingDialog();
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        LoadingDialog.closeLoadingDialog();

        // 获取验证码
        if (response.getUrlParam() == UrlParam.reqSendCode) {
            if (!response.isOk()) {
                PToast.showLong(TextUtils.isEmpty(response.getMsg()) ? "获取失败，请重试" : response.getMsg());
                return;
            }
            et_code.requestFocus();
            if (sendthread == null || sendthread.getState() == State.TERMINATED) {
                sendthread = new SendEnableThread();
                sendthread.start();
            }
        }

        // 绑定结果
        if (response.getUrlParam() == UrlParam.reqBindMobile) {
            if (!response.isOk()) {
                PToast.showShort(TextUtils.isEmpty(response.getMsg()) ? "绑定失败，请重试" : response.getMsg());
                return;
            }
            MsgMgr.getInstance().sendMsg(MsgType.MT_Update_MyInfo, null);
            ModuleMgr.getCenterMgr().getMyInfo().setCell_phone(phone);
            PToast.showShort("绑定成功");
            finish();
        }
    }

    // ============== 倒计时 ===============
    private final MyHandler m_Handler = new MyHandler(this);
    private SendEnableThread sendthread = null;

    private static class MyHandler extends Handler {
        private final WeakReference<PhoneVerifyAct> mActivity;

        MyHandler(PhoneVerifyAct act) {
            this.mActivity = new WeakReference<>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            PhoneVerifyAct act = mActivity.get();
            if (act != null) {
                if (msg.what > 0) {
                    act.bt_send_code.setText(String.format(act.getString(R.string.bt_send_code_press), msg.what));
                } else {
                    act.bt_send_code.setText(act.getResources().getString(R.string.bt_send_code_normal));
                }
            }
        }
    }

    private class SendEnableThread extends Thread {
        public void run() {
            int count = 60;
            while (count >= 0) {
                try {
                    Thread.sleep(1000);
                    m_Handler.sendEmptyMessage(count);
                } catch (Exception e) {
                    break;
                }
                count--;
            }
        }
    }
}
